package fun.liuyu2783.txmessage.trade.controller;

import fun.liuyu2783.txmessage.common.MqConstant;
import fun.liuyu2783.txmessage.common.Response;
import fun.liuyu2783.txmessage.trade.dto.Trade;
import fun.liuyu2783.txmessage.trade.service.TradeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuyu2783
 * @since 2021-11-23
 */
@Slf4j
@RestController
@RequestMapping("/trade")
public class TradeController {

    @Autowired
    private TradeService tradeService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @PostMapping("confirm")
    @Transactional(rollbackFor = {Exception.class})
    public Response confirmTrade(@RequestBody Trade trade1){
        Trade trade = new Trade();
        String orderId = UUID.randomUUID().toString();
        trade.setId(orderId);
        trade.setGoodsId("1");
        trade.setGoodsName("可口可乐");
        trade.setName("liuyu2783");
        trade.setCreateTime(new Date());
        boolean save = tradeService.save(trade);
        if(save){
            rocketMQTemplate.sendMessageInTransaction(MqConstant.TRADE_TRANSACTION_PRODUCER_GROUP, MqConstant.TOPIC_TRADE_TRANSACTION, MessageBuilder.withPayload(trade).build(), null);
        }
        return Response.success();
    }

}

